﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AdministracionCooperativa.Controlador;
using AdministracionCooperativa.entidades;
using System.Collections;


namespace AdministracionCooperativa.Formularios
{
    public partial class formcu : Form
    {
        private List<tblreg> listaPagosACobrar = null;
        private int costoPosturero = 0;
        public formcu()
        {
            InitializeComponent();
        }

        private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void formcu_Load(object sender, EventArgs e)
        {
            InicializarControles();
            textBox3.KeyPress += new KeyPressEventHandler(Valida_Numeros);
            textBox4.KeyPress += new KeyPressEventHandler(Valida_Numeros);
            textBox5.KeyPress += new KeyPressEventHandler(Valida_Numeros);
            textBox6.KeyPress += new KeyPressEventHandler(Valida_Numeros);
            textBox10.KeyPress += new KeyPressEventHandler(Valida_Numeros);
            textBox9.KeyPress += new KeyPressEventHandler(Valida_Numeros);
            textBox8.KeyPress += new KeyPressEventHandler(Valida_Numeros);
            textBox7.KeyPress += new KeyPressEventHandler(Valida_Numeros);
        }
        private void ActualizarLista()
        {
            var totalitems=listView1.Items.Count;
            var aux = totalitems;
            for (int i = totalitems; i > 0; i--)
            {
                listView1.Items.RemoveAt(i-1);
            }
        }
        private void InicializarControles()
        {
            ActualizarLista();
            label5.Text = string.Empty;
            label6.Text = string.Empty;
            label12.Text = "0.0";
            detalleuni.Visible = false;
            button1.Enabled = false;
            textBox1.Text = string.Empty;
            textBox1.Focus();
        }

        private void LlenarLista(string unidad)
        {
            ActualizarLista();
            button1.Enabled = true;
            //label12.Text ="";
            foreach (var item in listaPagosACobrar)
            {
                ListViewItem item1 = listView1.Items.Add(item.FECHA.ToShortDateString());
                item1.SubItems.Add(ControlodarRegistroCouta.CalcularTotal(item).ToString());
                item1.SubItems.Add(item.IDREG.ToString());
                item1.Tag = item;
                item1.Name = item.FECHA.ToShortDateString();
                item1.Checked = true;
            }
            if (listView1.Items.Count > 4)
            {
                Size tempSize = pB3.Size;
                tempSize.Width = 203;
                pB3.Size = tempSize;
            }
            else
            {
                Size tempSize = pB3.Size;
                tempSize.Width = 220;
                pB3.Size = tempSize;
            }
        }
        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            detalleuni.Visible = true;
            var t = (tblreg)e.Item.Tag;
            textBox3.Text = Convert.ToInt32(t.CUOTA).ToString();
            textBox4.Text = Convert.ToInt32(t.SEGCHO).ToString();
            textBox5.Text =Convert.ToInt32( t.CHECADOR).ToString();
            textBox6.Text = Convert.ToInt32(t.SUBBAR).ToString();
            textBox10.Text = Convert.ToInt32(t.TEMP).ToString();
            textBox9.Text = Convert.ToInt32(t.SEGIMSS).ToString();
            textBox8.Text = Convert.ToInt32(t.COOSOC).ToString();
            textBox7.Text = Convert.ToInt32(t.POSTURERO).ToString();
            costoPosturero = Convert.ToInt32(t.POSTURERO);
            checkBox4.Checked = (bool)ControladorUnidad.unidadActual.PAGPOS;
            checkBox3.Checked = (bool)ControladorUnidad.unidadActual.PAGSOC;
            checkBox2.Checked = (bool)ControladorUnidad.unidadActual.PAGSUB;
            if (checkBox4.Checked && e.Item.SubItems[2].Text=="-1")
                textBox7.Text = Convert.ToInt32(ControladorUnidad.unidadActual.COSTOPOS).ToString();
                        
        }
        private void Valida_Numeros(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsDigit(e.KeyChar) | char.IsControl(e.KeyChar) | char.IsPunctuation(e.KeyChar)))
            {
                e.Handled = true;
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsDigit(e.KeyChar) | char.IsControl(e.KeyChar)))
            {
                e.Handled = true;
            }
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                if (!string.IsNullOrWhiteSpace(textBox1.Text.Trim()))
                {
                    textBox1.Text=Convert.ToInt32(textBox1.Text.ToString()).ToString("D4");
                    if (ControladorUnidad.ExisteUnidad(this.textBox1.Text))
                    {
                        ControladorUnidad.EstablecerUnidad(this.textBox1.Text);
                        listaPagosACobrar = ControlodarRegistroCouta.ObtenerAdeudosByUnidad(ControladorUnidad.unidadActual.NUMUNI);
                        if (listaPagosACobrar != null)
                        {
                            ControladorChofer.EstableceDatosChofer(ControladorUnidad.unidadActual.CATCHO_SEGSOC);
                            var nameChofer = ControladorChofer.NombreCompleto;
                            label6.Text = nameChofer;
                            label5.Text = ControladorCuota.obtenerCouta(ControladorUnidad.unidadActual.CATCOU_idCOU).TIPO;
                            LlenarLista(textBox1.Text);
                            checkBox1.Checked = ControlodarRegistroCouta.EstaEnTaller(ControladorUnidad.unidadActual.NUMUNI);
                        }
                        else
                        {
                            MessageBox.Show("Esta unidad ya pagó el Día de hoy", "CONTTAS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            InicializarControles();
                        }
                    }
                    else
                    {
                        MessageBox.Show("No existe unidad. Verificar", "CONTTAS", MessageBoxButtons.OK, MessageBoxIcon.Error);
                       
                    }
                }
                textBox1.Select(0, textBox1.Text.Length);
                textBox1.Focus();
                e.Handled = false;
            }
            
        }
        private string ValidarTextBox()
        {
            var mensaje = string.Empty;
            var controles = this.Controls["detalleuni"];
            foreach (var item in controles.Controls)
            {
                decimal valor;
                if (item is TextBox)
                {
                    var controltext = (TextBox)item;
                    if (!decimal.TryParse(controltext.Text.ToString(),out valor))
                        mensaje += "El Valor : " + controltext.Text + ", no es un número válido. \n";
                }
            }

            return mensaje;
        }
        private bool ValidarExistanElementos()
        {
            var resultado=true;
            resultado = listView1.Items.Count>0;
            resultado = listView1.Items.Cast<ListViewItem>().Any(i => i.Checked == true);
            return resultado;
        }
            
            
        /// <summary>
        /// Metodo para actualizar los pagos o insertar uno nuevo
        /// </summary>
        private void button3_Click(object sender, EventArgs e)
        {
            var errores = ValidarTextBox();
            if(!string.IsNullOrWhiteSpace(errores))
                MessageBox.Show("Errores al Capturar: "+errores, "CONTTAS", MessageBoxButtons.OK, MessageBoxIcon.Error);
            else
            {
                var item = listView1.SelectedItems[0];
                var t = (tblreg)item.Tag;
                t.CUOTA = Convert.ToDecimal(textBox3.Text.ToString());
                t.SEGCHO = Convert.ToDecimal(textBox4.Text.ToString());
                t.CHECADOR= Convert.ToDecimal(textBox5.Text.ToString());
                t.SUBBAR = Convert.ToDecimal(textBox6.Text.ToString());
                t.TEMP= Convert.ToDecimal(textBox10.Text.ToString());
                t.SEGIMSS= Convert.ToDecimal(textBox9.Text.ToString());
                t.COOSOC= Convert.ToDecimal(textBox8.Text.ToString());
                t.POSTURERO = Convert.ToDecimal(textBox7.Text.ToString());
                var u = ControladorUnidad.unidadActual;
                u.PAGSUB = checkBox2.Checked;
                u.PAGSOC = checkBox3.Checked;
                u.PAGPOS = checkBox4.Checked;
                u.COSTOPOS = t.POSTURERO;
                var ue = ControladorUnidad.Guardar(u);
                var idnuevo = ControlodarRegistroCouta.Guardar(t);
                t.IDREG = idnuevo;
                listView1.SelectedItems[0].Tag = t;
                listView1.SelectedItems[0].SubItems[2].Text = idnuevo.ToString();
                listView1.SelectedItems[0].SubItems[1].Text = ControlodarRegistroCouta.CalcularTotal(t).ToString();
                listView1.Items[item.Index].Selected = true;
                var total = listView1.Items.Cast<ListViewItem>().Where(i=>i.Checked==true).Sum(i => Convert.ToDecimal(i.SubItems[1].Text.ToString()));
                label12.Text = total.ToString();
            }
        }

        private void listView1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            decimal temp = Decimal.Parse(label12.Text.ToString());
            decimal valor = Decimal.Parse(listView1.Items[e.Index].SubItems[1].Text);
            if (e.CurrentValue == CheckState.Checked)
                temp -= valor;
            else
                temp += valor;
            label12.Text = temp.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (ValidarExistanElementos())
            {
                var u = listView1.Items.Cast<ListViewItem>().Any(i => i.SubItems[2].Text == "-1");
                if (u)
                {
                    MessageBox.Show("No ha guardado el cobro de hoy", "CONTTAS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    PrintDocument ticket = new PrintDocument();
                    var ids = listView1.Items.Cast<ListViewItem>().Select(i => Convert.ToInt64(i.SubItems[2].Text)).ToList();
                    listaPagosACobrar = ControlodarRegistroCouta.ModificarEstatus(ids);
                    ticket.PrintPage += new PrintPageEventHandler(Datos_Ticket);
                    ticket.Print();
                }
            }
            else
            {
                MessageBox.Show("No hay información a imprimir.", "CONTTAS", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void Datos_Ticket(object obj, PrintPageEventArgs ev)
        {
            ev.Graphics.PageUnit = GraphicsUnit.Millimeter;
            ImprimirTicket.Imprimir(ev.Graphics, listaPagosACobrar);
            InicializarControles();
        }

        private void textBox1_MouseClick(object sender, MouseEventArgs e)
        {
            InicializarControles();
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked == false)
                textBox6.Text = "0";
            else
            {
                if (listView1.SelectedItems.Count>0)
                {
                    var t = (tblreg)listView1.SelectedItems[0].Tag;
                    textBox6.Text = Convert.ToInt32(t.SUBBAR).ToString();
                }
            }
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox3.Checked == false)
                textBox8.Text = "0";
            else
            {
                if (listView1.SelectedItems.Count > 0)
                {
                    var t = (tblreg)listView1.SelectedItems[0].Tag;
                    textBox8.Text = Convert.ToInt32(t.COOSOC).ToString();
                }
            }
        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox4.Checked == false)
                textBox7.Text = "0";
            else
            {
                if (listView1.SelectedItems.Count > 0)
                {
                    textBox7.Text = costoPosturero.ToString();
                }
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
           
        }

        private void checkBox1_CheckStateChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
                textBox3.Text = "0";
            else
                if (listView1.SelectedItems.Count > 0)
                {
                    var t = (tblreg)listView1.SelectedItems[0].Tag;
                    textBox3.Text = Convert.ToInt32(t.CUOTA).ToString();
                }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.OpenForms["formcu"].Close();
        }
    }
}
